package com.ruoyi.report.controller;

import java.lang.reflect.Type;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.report.domain.DepotJsonDto;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.report.domain.ReportDc;
import com.ruoyi.report.service.IReportDcService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 配送中心Controller
 * 
 * @author ruoyi
 * @date 2024-10-15
 */
@RestController
@RequestMapping("/dc/dc")
public class ReportDcController extends BaseController
{
    @Autowired
    private IReportDcService reportDcService;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询配送中心列表
     */
    @PreAuthorize("@ss.hasPermi('dc:dc:list')")
    @GetMapping("/list")
    public TableDataInfo list(ReportDc reportDc)
    {
        startPage();
        List<ReportDc> list = reportDcService.selectReportDcList(reportDc);
        return getDataTable(list);
    }
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISysDeptService deptService;
    /**
     * 导出配送中心列表
     */
    @PreAuthorize("@ss.hasPermi('dc:dc:export')")
    @Log(title = "配送中心", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response,ReportDc reportDc)
    {
        Gson gson = new Gson();
        List<ReportDc> list = reportDcService.selectReportDcList(reportDc);
        //查询出所有部门
        List<SysDept> sysDepts = deptService.selectDeptList(new SysDept());
        List<SysUser> sysUsers = userMapper.selectUserList(new SysUser());
        for (ReportDc dc : list) {
//            SysUser correspondingWork = sysUsers.stream()
//                    .filter(user -> user.getUserId().equals(dc.getWorkUserId()))
//                    .findFirst()
//                    .orElse(null);
//            dc.setWorkName(ObjectUtil.isNotEmpty(correspondingWork)?correspondingWork.getUserName():"");
            String extra2 = dc.getExtra2();
            Type userType = new TypeToken<List<Long>>() {}.getType();
            List<Long> uids = gson.fromJson(extra2, userType);

            List<SysUser> correspondingReports = sysUsers.stream()
                    .filter(user -> uids.contains(user.getUserId())) // Assumes `ReportUserId` is now a collection of user IDs
                    .collect(Collectors.toList());

            String workNames = correspondingReports.stream()
                    .map(SysUser::getUserName)
                    .collect(Collectors.joining(", "));

            dc.setWorkName(workNames);

            SysUser correspondingReport = sysUsers.stream()
                    .filter(user -> user.getUserId().equals(dc.getReportUserId()))
                    .findFirst()
                    .orElse(null);
            dc.setReportName(ObjectUtil.isNotEmpty(correspondingReport)?correspondingReport.getUserName():"");

            SysDept correspondingDept = sysDepts.stream()
                    .filter(dept -> dept.getDeptId().equals(dc.getDeptId()))
                    .findFirst()
                    .orElse(null);

            dc.setDeptName(ObjectUtil.isNotNull(correspondingDept)?correspondingDept.getDeptName():"");

        }

        ExcelUtil<ReportDc> util = new ExcelUtil<ReportDc>(ReportDc.class);
         util.exportExcel(response,list, "配送中心数据");
    }

    /**
     * 获取配送中心详细信息
     */
    @PreAuthorize("@ss.hasPermi('dc:dc:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(reportDcService.selectReportDcById(id));
    }

    /**
     * 新增配送中心
     */
    @PreAuthorize("@ss.hasPermi('dc:dc:add')")
    @Log(title = "配送中心", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ReportDc reportDc)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        reportDc.setDeptId(loginUser.getUser().getDept().getDeptId());
        reportDc.setCreateTime(DateUtils.getNowDate());

        Integer i = reportDcService.countTodayRecordsDc(reportDc.getDeptId());
        if (i>=1){
            throw new RuntimeException("今日已有数据上报记录,请前往修改");
        }
        Gson gson = new Gson();
        List<DepotJsonDto> extra1 = reportDc.getExtra1();
        List<DepotJsonDto> sendJson = reportDc.getSendJson();
        if (CollectionUtil.isNotEmpty(extra1)){
            reportDc.setExtra3(gson.toJson(extra1));
            reportDc.setExtra4(gson.toJson(sendJson));
        }


        reportDc.setExtra1(null);
        reportDc.setSendJson(null);
        List<Long> workUsers = reportDc.getWorkUsers();
        if (CollectionUtil.isNotEmpty(workUsers)){
            reportDc.setExtra2(gson.toJson(workUsers));
        }
        return toAjax(reportDcService.insertReportDc(reportDc));
    }

    /**
     * 修改配送中心
     */
    @PreAuthorize("@ss.hasPermi('dc:dc:edit')")
    @Log(title = "配送中心", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ReportDc reportDc)
    {
        Gson gson = new Gson();
        List<DepotJsonDto> extra1 = reportDc.getExtra1();
        List<DepotJsonDto> sendJson = reportDc.getSendJson();
        if (CollectionUtil.isNotEmpty(extra1)){
            reportDc.setExtra3(gson.toJson(extra1));
            reportDc.setExtra4(gson.toJson(sendJson));
        }
        reportDc.setExtra1(null);
        reportDc.setSendJson(null);
        List<Long> workUsers = reportDc.getWorkUsers();
        if (CollectionUtil.isNotEmpty(workUsers)){
            reportDc.setExtra2(gson.toJson(workUsers));
        }
        return toAjax(reportDcService.updateReportDc(reportDc));
    }
    

    /**
     * 删除配送中心
     */
    @PreAuthorize("@ss.hasPermi('dc:dc:remove')")
    @Log(title = "配送中心", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(reportDcService.deleteReportDcByIds(ids));
    }
}
